<template>
  <div curpagename="s5goortyueryert5352" ref="filterBtnRef">
    <el-badge :value="badge" :max="99" class="item" :show-zero="false">
      <el-button
        type="default"
        class="filter_btn"
        :class="{ active: popoverVisible }"
        v-popover="popoverRef"
        v-click-outside="onClickOutside"
        @click="showAdvancedModal"
        title="货号、型号批量搜索"
      >
      <el-icon><Aim /></el-icon>
      </el-button>
    </el-badge>

    <el-popover
      popper-class="custom_search_popover"
      transition="el-zoom-in-top"
      :popoverVisible="popoverVisible"
      :offset="popoverOffset"
      placement="bottom"
      :popper-style="popperStyle"
      trigger="click"
      ref="popoverRef"
    >
      <div class="modal" ref="popoverModalFef">
        <el-form ref="formRef" :model="customSearchFormData" label-position="top" :rules="customSearchRules">
          <div class="select_search_type">
            <el-form-item label="" prop="radio">
              <el-radio-group v-model="customSearchFormData.radio">
                <el-radio value="sku">{{$t("base_markings.sku")}}</el-radio>
                <el-radio value="supplier_sku">{{$t("base_markings.supplier_sku")}}</el-radio>
                <el-radio value="spu">{{$t("goods_archive.spu")}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div>
            <el-form-item label="" prop="textAreaValue">
              <el-input
                class="custom_search_text"
                v-model="customSearchFormData.textAreaValue"
                autocomplete=""
                type="textarea"
                resize="none"
                :placeholder="customSearchTextAreaPlaceholder"
              />
            </el-form-item>
          </div>
        </el-form>
        <div class="custom_footer">
          <el-button @click="search(formRef,0)">{{$t("merak.fuzzy_search")}}</el-button>
          <el-button type="primary" @click="search(formRef,1)">{{$t("merak.accurate_search")}}</el-button>  
          
        </div>
      </div>
    </el-popover>
  </div>
</template>
<script setup lang='ts' name='customSearch03958'>
import { ref, reactive, getCurrentInstance, onMounted, nextTick, unref, inject, computed } from "vue";
import { ClickOutside as vClickOutside } from "element-plus";
import { composeEventHandlers } from "element-plus/es/utils";
import { cosDependencies } from "mathjs";
const { proxy } = getCurrentInstance();

const props = defineProps(["searchBarRef"]);

let popoverOffset: number = 8; //默认向上偏移量
let popoverVisible = ref<boolean>(false); //搜索弹出框值
let popperStyle = ref<object>({}); //默认弹出框宽自定义样式 ，禁止设置top值
let filterBtnRef = ref();
let searchPopverRef = ref();
let formRef = ref();
let popoverModalFef = ref();
let timer = null;

let customSearchFormData = inject("customSearchFormData");
let customSearchRules = inject("customSearchRules"); 
let customSearchTextAreaPlaceholder = inject("customSearchTextAreaPlaceholder");
let customSearchHandle = inject("customSearchHandle");

const search = (formRef,is_like) => {
  formRef?.validate(valid => {
    if (valid) {
      customSearchHandle.search({ customSearchType: customSearchFormData.radio, value: customSearchFormData.textAreaValue,is_like:is_like });
    } else {
    }
  });
  //
};

/**
 * 计算属性，用于获取自定义搜索表单文本区域中输入的标签数量。
 *
 * 该计算属性通过处理文本区域中的字符串，将字符串按逗号分隔为列表，并返回列表的长度。
 * 这样做的目的是为了动态地根据用户输入的标签数量来更新徽章（badge）的显示，徽章通常用于表示项目数量。
 *
 * @returns {Number} 返回标签列表的长度，代表了输入文本区域中的标签数量。
 */
const badge = computed(() => {
  // 初始化一个空列表，用于存储分隔后的标签。
  let list = [];
  // 获取文本区域的值，如果值不存在，则默认为空字符串。
  let textAreaValue = customSearchFormData.textAreaValue ?? "";

  // 检查文本区域的值是否包含逗号，如果包含，则进行处理。
  if (textAreaValue.indexOf(",") != -1) {
    // 移除字符串两端的逗号，以确保列表元素不包含逗号。
    textAreaValue = textAreaValue.replace(/^,|,$/gi, "");
    // 将处理后的字符串按逗号分隔为列表。
    list = textAreaValue.split(",");
  }

  // 返回列表的长度，即标签的数量。
  return list.length;
});

const showAdvancedModal = () => {
  popoverVisible.value = !popoverVisible.value;

  //   document.addEventListener("keydown", tabfn);
  // bus.planOptions = planOptions;
  setAdvancedModalStyle();
};

const popoverRef = ref();
const onClickOutside = () => {
  popoverVisible.value = false;
  unref(popoverRef).popperRef?.delayHide?.();
};

onMounted(() => {
  //高搜索弹出框 挂载后设置 width和 left
  setAdvancedModalStyle();
//   window.addEventListener("resize", handleResize);
  customSearchHandle.getFormInstance(formRef);
});

// methods
const handleResize = () => {
  clearTimeout(timer);
  timer = setTimeout(() => {
    setAdvancedModalStyle();
  }, 100);
};
const curAttr = ref<string>("");
const labelClass = ref<string>("");

const getOffsetBody = (ele: any) => {
  let curEle = ele;
  let leftVal: number = 0;
  let topVal: number = 0;
  while (curEle?.offsetParent) {
    leftVal += curEle.offsetLeft;
    topVal += curEle.offsetTop;
    curEle = curEle.offsetParent;
  }
  return { left: leftVal, top: topVal };
};

const setAdvancedModalStyle = () => {
  let ele = document.querySelector(".search_bar");
  console.log(ele);
  let offset = getOffsetBody(ele);
  console.log(offset);

  let btnOffset = getOffsetBody(filterBtnRef.value);
  console.log(btnOffset);
  popperStyle.value = {
    left: offset.left + "px",
    width: ele?.clientWidth / 2 + "px",
    // width: 600+"px",
    // height: document.documentElement.clientHeight - offset.top - ele.clientHeight - 50 + "px"
    height: 400 + "px"
  };
  nextTick(() => {
    setTimeout(() => {
      document.querySelector(".custom_search_popover").querySelector(".el-popper__arrow").style.left =
        btnOffset.left - offset.left + (filterBtnRef.value.clientWidth / 2 - 8) + "px";
    }, 10);
  });
  // console.log(popoverModalFef.value )
};
</script>
<style lang='scss' scoped>
.modal {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
}
.filter_btn {
  padding: 15px;
  min-width: 32px;
  width: 32px;
  font-size: 19px;
  color: var(--el-button-disabled-text-color);
  &:hover {
    //  custom
    color: var(--el-button-hover-text-color) !important;
  }
  &:focus,
  &:active {
    color: var(--el-button-disabled-text-color) !important;
  }

  &.active {
    //  custom
    color: var(--el-button-hover-text-color) !important;
    border-color: var(--el-button-hover-border-color) !important;
    background-color: transparent;
  }
}
:deep(.custom_search_text .el-textarea__inner) {
  width: 100%;
  height: 220px;
}

.select_search_type {
  padding: 10px;
}
.custom_footer {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 15px 0px;
}

</style>
<style  >
.custom_search_popover {
    padding:10px 30px 10px !important;
 }

</style>
